import os
import shutil
import zipfile
import datetime
import time
import sys

def package_project():
    # 创建打包时间戳
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    package_name = f"box-admin_{timestamp}"
    
    # 创建临时目录
    if not os.path.exists("dist"):
        os.mkdir("dist")
    
    temp_dir = os.path.join("dist", package_name)
    if os.path.exists(temp_dir):
        try:
            shutil.rmtree(temp_dir)
        except PermissionError:
            print(f"无法删除临时目录 {temp_dir}，尝试使用其他名称...")
            package_name = f"box-admin_{timestamp}_retry"
            temp_dir = os.path.join("dist", package_name)
    
    os.mkdir(temp_dir)
    
    # 需要复制的文件和目录
    to_copy = [
        "app",
        "app.py",
        "requirements.txt",
        "README.md"
    ]
    
    # 复制文件
    for item in to_copy:
        src = os.path.join(os.path.dirname(os.path.dirname(__file__)), item)
        dst = os.path.join(temp_dir, item)
        
        try:
            if os.path.isdir(src):
                shutil.copytree(src, dst, ignore=shutil.ignore_patterns(
                    '*.pyc', '*__pycache__*', '.git', '.vscode', '*.log', '*.tmp'
                ))
            else:
                shutil.copy2(src, dst)
        except FileNotFoundError as e:
            print(f"警告: 找不到文件 {src}，已跳过")
    
    # 创建zip文件
    zip_filename = os.path.join("dist", f"{package_name}.zip")
    with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(temp_dir):
            for file in files:
                file_path = os.path.join(root, file)
                arcname = os.path.relpath(file_path, "dist")
                zipf.write(file_path, arcname)
    
    # 清理临时目录，增加重试机制
    max_retries = 3
    for attempt in range(max_retries):
        try:
            for root, dirs, files in os.walk(temp_dir, topdown=False):
                for file in files:
                    try:
                        os.chmod(os.path.join(root, file), 0o777)  # 尝试更改文件权限
                    except:
                        pass
            
            # 等待一小段时间，让系统释放文件句柄
            time.sleep(1)
            shutil.rmtree(temp_dir)
            break
        except Exception as e:
            print(f"尝试 {attempt+1}/{max_retries} 清理目录失败: {str(e)}")
            if attempt == max_retries - 1:
                print(f"警告: 无法删除临时目录 {temp_dir}，请在打包完成后手动删除。")
    
    print(f"项目已打包为: {zip_filename}")
    return zip_filename

if __name__ == "__main__":
    try:
        package_project()
    except Exception as e:
        print(f"打包过程中出错: {str(e)}")
        sys.exit(1) 

